package cn.iocoder.yudao.module.dr.service.collectionmanagement;

import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.*;
import cn.iocoder.yudao.module.dr.controller.admin.report.vo.index.DeptUseDataRespVO;
import cn.iocoder.yudao.module.dr.controller.admin.report.vo.index.FileTypeDataRespVO;
import cn.iocoder.yudao.module.dr.controller.admin.report.vo.index.SourceTypeDataRespVO;
import cn.iocoder.yudao.module.dr.controller.admin.report.vo.index.VisitDataRespVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionlinkaddress.CollectionLinkAddressDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionmanagement.CollectionManagementDO;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionlinkaddress.CollectionLinkAddressMapper;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionmanagement.CollectionManagementMapper;
import cn.iocoder.yudao.module.dr.service.collection3dacquisition.Collection3dAcquisitionService;
import cn.iocoder.yudao.module.dr.service.collectionimageacquisition.CollectionImageAcquisitionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dr.enums.ErrorCodeConstants.COLLECTION_MANAGEMENT_NOT_EXISTS;

/**
 * 藏品管理 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class CollectionManagementServiceImpl implements CollectionManagementService {

    @Resource
    private CollectionManagementMapper collectionManagementMapper;

    @Resource
    private Collection3dAcquisitionService collection3dAcquisitionService;

    @Resource
    private CollectionImageAcquisitionService collectionImageAcquisitionService;

    @Resource
    private CollectionLinkAddressMapper collectionLinkAddressMapper;

    @Override
    public CollectionManagementRespVO createCollectionManagement(CollectionManagementSaveReqVO createReqVO) {
        // 插入
        CollectionManagementDO collectionManagement = BeanUtils.toBean(createReqVO, CollectionManagementDO.class);
        collectionManagementMapper.insert(collectionManagement);

        createReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("1"));
        // 插入子表
        createCollectionLinkAddressList(collectionManagement.getId(), createReqVO.getCollectionLinkAddress());
        // 返回
        return BeanUtils.toBean(collectionManagement, CollectionManagementRespVO.class);
    }

    @Override
    public CollectionManagementRespVO updateCollectionManagement(CollectionManagementSaveReqVO updateReqVO) {
        // 校验存在
        validateCollectionManagementExists(updateReqVO.getId());
        // 更新
        CollectionManagementDO updateObj = BeanUtils.toBean(updateReqVO, CollectionManagementDO.class);
        collectionManagementMapper.updateById(updateObj);
        // 更新子表
        updateReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("1"));
        updateCollectionLinkAddressList(updateReqVO.getId(),"1", updateReqVO.getCollectionLinkAddress());
        return BeanUtils.toBean(updateObj, CollectionManagementRespVO.class);
    }

    @Override
    public void deleteCollectionManagement(Long id) {
        // 校验存在
        validateCollectionManagementExists(id);
        // 删除
        collectionManagementMapper.deleteById(id);
    }

    private void validateCollectionManagementExists(Long id) {
        if (collectionManagementMapper.selectById(id) == null) {
            throw exception(COLLECTION_MANAGEMENT_NOT_EXISTS);
        }
    }

    @Override
    public CollectionManagementDO getCollectionManagement(Long id) {
        return collectionManagementMapper.selectById(id);
    }

    @Override
    public PageResult<CollectionManagementDO> getCollectionManagementPage(CollectionManagementPageReqVO pageReqVO) {
        return collectionManagementMapper.selectPage(pageReqVO);
    }

    @Override
    public CollectionManagementDO selectByGeneralAccessionNumber(String generalAccessionNumber) {
        LambdaQueryWrapper<CollectionManagementDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CollectionManagementDO::getGeneralAccessionNumber, generalAccessionNumber);
        queryWrapper.eq(CollectionManagementDO::getDeleted, false);
        return collectionManagementMapper.selectOne(queryWrapper);
    }

    @Override
    public CollectionImportRespVO importDataList(MultipartFile file, Boolean updateSupport, Integer importType) {
        CollectionImportRespVO respVO = CollectionImportRespVO.builder().createNames(new ArrayList<>())
                .updateNames(new ArrayList<>()).failureNames(new LinkedHashMap<>()).build();
        try {
            switch (importType){
                case 1:
                    List<CollectionImportExcelVO> cList = ExcelUtils.read(file, CollectionImportExcelVO.class,2);
                    respVO = this.saveImportDataList(cList, updateSupport, importType);
                    break;
                case 2:
                    List<CollectionImageImportExcelVO> iList = ExcelUtils.read(file, CollectionImageImportExcelVO.class,2);
                    respVO = collectionImageAcquisitionService.saveImportDataList(this,iList, updateSupport, importType);
                    break;
                case 3:
                    List<Collection3dImportIndexVO> dList = ExcelUtils.read(file, Collection3dImportIndexVO.class,3);
                    respVO = collection3dAcquisitionService.saveImportDataList(this,dList, updateSupport, importType);
                    break;
                default:
                    throw exception(GlobalErrorCodeConstants.TEMPLATE_NOT_EXISTS);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return respVO;
    }


    public CollectionImportRespVO saveImportDataList(List<CollectionImportExcelVO> list, Boolean updateSupport, Integer importType) {

        CollectionImportRespVO respVO = CollectionImportRespVO.builder().createNames(new ArrayList<>())
                .updateNames(new ArrayList<>()).failureNames(new LinkedHashMap<>()).build();

        CollectionManagementDO collectionManagementDO;
        for (CollectionImportExcelVO d : list) {
            collectionManagementDO  = new CollectionManagementDO();
            CollectionManagementDO exist = collectionManagementMapper.selectByGeneralAccessionNumber(d.getGeneralAccessionNumber());
            if (exist != null) {
                if (updateSupport) {
                    BeanUtils.copyProperties(d, collectionManagementDO);
                    collectionManagementDO.setId(exist.getId());
                    collectionManagementMapper.updateById(collectionManagementDO);
                    respVO.getUpdateNames().add(d.getName());
                } else {
                    respVO.getFailureNames().put(d.getGeneralAccessionNumber(), "藏品总登记号已存在");
                }
                continue;
            }
            BeanUtils.copyProperties(d, collectionManagementDO);
            collectionManagementMapper.insert(collectionManagementDO);
            respVO.getCreateNames().add(d.getName());

        }
        return respVO;
    }


    @Override
    public List<CollectionLinkAddressDO> getCollectionLinkAddressListByCollectionId(Long collectionId,String bizType) {
        return collectionLinkAddressMapper.selectListByCollectionId(collectionId,bizType);
    }

    @Override
    public List<SourceTypeDataRespVO> countByLevel() {
        return collectionLinkAddressMapper.countByLevel();
    }

    @Override
    public List<FileTypeDataRespVO> countBySource() {
        return collectionLinkAddressMapper.countBySource();
    }

    @Override
    public List<DeptUseDataRespVO> countByDegree() {
        return collectionLinkAddressMapper.countByDegree();
    }

    @Override
    public List<VisitDataRespVO> countByCategory() {
        return collectionLinkAddressMapper.countByCategory();
    }

    private void createCollectionLinkAddressList(Long collectionId, List<CollectionLinkAddressDO> list) {
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setCollectionId(collectionId));
        collectionLinkAddressMapper.insertBatch(list);
    }

    private void updateCollectionLinkAddressList(Long collectionId,String bizType, List<CollectionLinkAddressDO> list) {
        deleteCollectionLinkAddressByCollectionId(collectionId, bizType);
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createCollectionLinkAddressList(collectionId, list);
    }

    private void deleteCollectionLinkAddressByCollectionId(Long collectionId,String bizType) {
        collectionLinkAddressMapper.deleteByCollectionIdAndBizType(collectionId,bizType);
    }


}